<?php
class TuneController extends mcz_Controller
{
	public function downloadAction($id)
	{
		$id = mcz_Crypt::decrypt(base64_decode($id));
		$parts = explode('::::', $id);
		if(count($parts) != 2)
		{
			die('Wrong request');
		}
		$res = mcz_DB::getInstance()->fetch('* from mcz_Tune where id = ?', array($parts[1]));
		if($res)
		{
			if($parts[0] == 'anonymous')
			{
				if(mcz_USE_AUTH)
				{
					die(T('Anonymous download is not allowed.'));
				}
			}
			else
			{
				$user = mcz_User::findOneByLogin($parts[0]);
				if(!$user)
				{
					die(T('No such user.'));
				}
				if(!$user->can('download'))
				{
					die(T('User is not allowed to download.'));
				}
			}
			$filename = preg_replace('/[^A-Za-z0-9_-]/', '_', $this->toascii($res[0]['artist'] . '_-_' . $res[0]['title'])) . '.mp3';
			$realLocation = str_replace('\\','/', mcz_TUNES_DIR . $res[0]['path']);
			session_write_close();
			//header('Content-type: ' . mime_content_type($realLocation));
			header('Content-type: audio/mpeg');
			header("Content-Length: " . filesize($realLocation));
			header("Content-Disposition: attachment; filename=" . $filename);
			readfile($realLocation);
		}
		die;
	}


	private function toascii($utfString)
	{
		return strtr(utf8_decode($utfString),
                     utf8_decode(
                      'ÀÁÂÃÄÅàáâãäåÒÓÔÕÖØòóôõöøÈÉÊËèéêëÇçÌÍÎÏìíîïÙÚÛÜùúûüÿÑñ'),
                      'AAAAAAaaaaaaOOOOOOooooooEEEEeeeeCcIIIIiiiiUUUUuuuuyNn');
	}

	public function listAction()
	{
		if(!isset($_POST['listaction']) or !isset($_POST['items']))
		{
			header('location: ' . $_SERVER['HTTP_REFERER']);
			die;
		}
		if($_POST['listaction'] == 'copy')
		{
			$tunes = mcz_Tune::findByIds($_POST['items']);
			foreach($tunes as $tune)
			{
				echo '<br/>' . mcz_TUNES_DIR . $tune->path;
				$filename = ereg_replace("[^A-Za-z0-9_-]","_",$this->toascii($tune->artist . '_-_' . $tune->title)) . '.mp3';
				$realLocation = str_replace('\\','/', mcz_TUNES_DIR . $tune->path);
				copy($realLocation, 'C:/Users/mickael/Desktop/selection/' . $filename);
			}
			die;
		}
		if($_POST['listaction'] == 'stream')
		{
			$this->sendM3u($_POST['items']);
		}
		if($_POST['listaction'] == 'playlist')
		{
			$pls = false;
			$plsTitle = trim($_POST['newPlaylistName']);
			if(!empty($plsTitle))
			{
				$pls = new mcz_Playlist();
				$pls->title = $plsTitle;
				$pls->user_id = $_SESSION['obj']->id;
				$pls->add($_POST['items']);
			}
			elseif(isset($_POST['existingPlaylist']))
			{
				$pls = mcz_Playlist::find($_POST['existingPlaylist']);
				if($pls)
				{
					$pls->add($_POST['items']);
				}
				else
				{
					throw new Exception('No such playlist.');
				}
			}
			header('location: ' . mczURL('playlist/show/' . $pls->id));
			die;
		}
	}

	public function sendM3u(array $ids)
	{
		header('content-type: audio/x-mpegurl');
		header("Content-Disposition: attachment; filename=" . uniqid('pls') . '.m3u');
		echo('#EXTM3U'. "\r\n");
		foreach($ids as $tuneId)
		{
			$tune = mcz_Tune::find($tuneId);
			echo('#EXTINF:' . $tune->time . ', ' . utf8_decode($tune->artist . ' - '. $tune->title) . "\r\n");
			if($_SERVER['SERVER_ADDR'] == $_SERVER['REMOTE_ADDR'])
			{
				echo(mcz_TUNES_DIR . $tune->path . "\r\n");
			}
			else
			{
				echo(mczURL('tune/download/') . base64_encode(mcz_Crypt::crypt($_SESSION['obj']->login . '::::' . $tuneId)) . "\r\n");
			}
		}
		die;
	}
	
	public function randomAction($limit = 30)
	{
		$return = array();
		$ids = mcz_DB::getInstance()->fetch('id from mcz_Tune order by random(id) limit ' . (int)$limit);
		foreach($ids as $row)
		{
			$return[] = $row['id'];
		}
		$this->sendM3u($return);
	}
}